import React from "react";
import { Form, DatePicker, Input, Select, Button, Col, InputNumber, TreeSelect } from "antd";
import * as Utils from "../../utils_yyr/action";
import moment from 'moment';
const FormItem = Form.Item;
const { Search } = Input;
const { RangePicker, MonthPicker } = DatePicker;
const { TreeNode } = TreeSelect;
class BasicForm extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      fieldsValue: {}
    }
  }
  componentDidMount() {
    this.props.onRef(this);
  }
  onSubmit = (type) => {
    const p = this;
    const { form } = p.props;
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (err) {
        return;
      }
      for (var key in fieldsValue) {
        //时间范围选择器
        if (key.indexOf("frame_") === 0) {
          if (fieldsValue[key] && fieldsValue[key].length) {
            let arr = key.split('_');
            fieldsValue[arr[1]] = Utils.getDate(fieldsValue[key][0])
            fieldsValue[arr[2]] = Utils.getDate(fieldsValue[key][1])
          }
          delete fieldsValue[key];
        }
        //单个时间选择器
        if (key.indexOf("date_") === 0) {
          if (fieldsValue[key]) {
            let arr = key.split('_');
            fieldsValue[arr[1]] = Utils.getDate(fieldsValue[key])
          }
          delete fieldsValue[key];
        }
        if (key.indexOf('dateSec_') === 0) {
          if (fieldsValue[key]) {
            let arr = key.split('_');
            fieldsValue[arr[1]] = Utils.getDateHHMMYY_HHMMSS(fieldsValue[key]);
          }
          delete fieldsValue[key];
        }

        //月选择器
        if (key.indexOf("month_") === 0) {
          if (fieldsValue[key]) {
            let arr = key.split('_');
            fieldsValue[arr[1]] = Utils.getStringByDate(fieldsValue[key], 'YYYY-MM')
          }
          delete fieldsValue[key];
        }
      }
      if (!type) {
        p.props.filterSubmit(fieldsValue)
      } else {
        return fieldsValue;
      }
    })
  }

  //获取表单的值
  getFormValues = () => {
    return this.onSubmit(true);
  }

  reset = () => {
    const p = this;
    p.props.form.resetFields();
  };
  renderTreeNodes = (data, name, valueField) =>
    // console.log(data, name, valueField)
    data && data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item[name]} key={item[valueField]} value={item[valueField]} dataRef={item}>
            {this.renderTreeNodes(item.children, name, valueField)}
          </TreeNode>
        );
      }
      return <TreeNode key={item[valueField]} value={item[valueField]} title={item[name]} {...item} />;
    });
    handlePanelChange = (value,fieldId) => {
      console.log(value)
      // test = value
      const p = this;
      let obj = {}
      obj[`${fieldId}`] = value
      p.props.form.setFieldsValue(obj)
      // this.setState({
      //   value,
      // });
    };

    handleChange = (value,fieldId) => {
      console.log(value)
      // test = value
      const p = this;
      let obj = {}
      obj[`${fieldId}`] = value
      p.props.form.setFieldsValue(obj)
      // this.setState({ value });
    };
  initFormList = () => {
    const p = this;
    const formItemList = [];
    const { getFieldDecorator } = p.props.form;
    const { formList } = p.props;
    // 页面上的表单
    if (formList && formList.length > 0) {
      formList.forEach(item => {
        const {
          label,
          field,
          type,
          valueField,
          name,
          showTime,
          col,
          onSearch,
          required,
          rules,
          placeholder,
          modeRule,
          multiple,
          // test,
        } = item;
        const mode = modeRule ? modeRule : ''
        const rulesType = rules ? rules : required ? [{ required: true, message: `${label}必填` }] : false;
        const initialValue = item.initialValue || undefined;
        if (type === "TIMEFRAME") {
          const timeFrame = (
            <Col span={col === undefined ? 6 : col}>
              <FormItem label={label} key={field} >
                {getFieldDecorator(`${field}`, {
                  rules: rulesType,
                  initialValue: initialValue && initialValue.length === 2 ? [moment(initialValue[0], 'YYYY-MM-DD'), moment(initialValue[1], 'YYYY-MM-DD')] : undefined, // true | false
                })(
                  <RangePicker
                    style={{ width: '100%' }}
                    showTime={showTime ? true : false}
                    placeholder={['开始时间', '结束时间']}
                    format={showTime ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD"}
                  />
                )}
              </FormItem>
            </Col>
          );
          formItemList.push(timeFrame);
        } if (type === "TIMEFRAMEMONTH") {
          const timeFrame = (
            <Col span={col === undefined ? 6 : col}>
              <FormItem label={label} key={field} >
                {getFieldDecorator(`${field}`, {
                  rules: rulesType,
                  initialValue: initialValue && initialValue.length === 2 ? [moment(initialValue[0], 'YYYY-MM'), moment(initialValue[1], 'YYYY-MM')] : undefined, // true | false
                })(
                  <RangePicker
                    // value={test}
                    style={{ width: '100%' }}
                    mode={['month', 'month']}
                    showTime={showTime ? true : false}
                    onChange={(value)=>this.handleChange(value,field)}
                    onPanelChange={(value)=>this.handlePanelChange(value,field)}
                    placeholder={['开始时间', '结束时间']}
                    format={showTime ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM"}
                  />
                )}
              </FormItem>
            </Col>
          );
          formItemList.push(timeFrame);
        } else if (type === "DATE") {
          const date = (
            <Col span={col === undefined ? 6 : col}>
              <FormItem label={label} key={field} >
                {getFieldDecorator(`${field}`, {
                  rules: rulesType,
                  initialValue: initialValue ? moment(initialValue, 'YYYY-MM-DD') : undefined, // true | false
                })(
                  <DatePicker
                    style={{ width: '100%' }}
                    placeholder='请选择日期'
                    showTime={showTime ? true : false}
                    format={showTime ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD"}
                  />
                )}
              </FormItem>
            </Col>
          );
          formItemList.push(date);
        } else if (type === "NUMBERFRAME") {
          let arr = field.split('_');
          const number = (
            <Col span={col === undefined ? 8 : col}>
              <Col span={12}>
                <FormItem label={label} key={field} >
                  {getFieldDecorator(`${arr[1]}`)(
                    <InputNumber style={{ width: '100%' }} placeholder='最高数量' />
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem key={field} >
                  {getFieldDecorator(`${arr[2]}`)(
                    <InputNumber style={{ width: '100%' }} placeholder='最低数量' max={p.props.form.getFieldValue(arr[1]) ? p.props.form.getFieldValue(arr[1]) : Infinity} />
                  )}
                </FormItem>
              </Col>

            </Col>
          );
          formItemList.push(number);
        } else if (type === "MONTHDATE") {
          const month = (
            <Col span={col === undefined ? 6 : col}>
              <FormItem label={label} key={field} >
                {getFieldDecorator(`${field}`, {
                  rules: rulesType,
                  initialValue: initialValue ? moment(initialValue, 'YYYY-MM') : undefined, // true | false
                })(
                  <MonthPicker
                    placeholder={`请选择${label}`}
                    style={{ width: '100%' }}
                    showTime={showTime ? true : false}
                  />
                )}
              </FormItem>
            </Col>
          );
          formItemList.push(month);
        } else if (type === "INPUT") {
          const INPUT = (
            <Col span={col === undefined ? 6 : col}>
              <FormItem key={field} label={label}>
                {getFieldDecorator(`${field}`, {
                  initialValue, // true | false
                  rules: rulesType,
                })(
                  <Input allowClear placeholder={placeholder ? placeholder : '请填写' + label} />
                )}
              </FormItem>
            </Col>
          );
          formItemList.push(INPUT);
        } else if (type === "SEARCH") {
          const SEARCH = (
            <Col span={col === undefined ? 6 : col}>
              <FormItem key={field} label={label}>
                {getFieldDecorator(`${field}`, {
                  initialValue, // true | false
                })(
                  <Search allowClear onSearch={(value) => onSearch(value)} enterButton placeholder={`请选择${label}`} />
                )}
              </FormItem>
            </Col>
          );
          formItemList.push(SEARCH);
        } else if (type === "SELECT") {
          const SELECT = (
            <Col span={col === undefined ? 6 : col}>
              <FormItem label={label} key={field}>
                {getFieldDecorator(`${field}`, {
                  initialValue, // true | false
                  rules: rulesType,
                })(
                  <Select placeholder={'请选择' + label}
                    showSearch
                    allowClear
                    mode={mode}
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {Utils.getOptionList(item.list, name, valueField)}
                  </Select>
                )}
              </FormItem>
            </Col>
          );
          formItemList.push(SELECT);
        } else if (item.type === 'TREESELECT') {
          const SELECT = (
            <Col span={col === undefined ? 6 : col}>
              <FormItem label={label} key={field}>
                {getFieldDecorator(`${field}`, {
                  rules: rulesType,
                  initialValue
                })(<TreeSelect onChange={this.onTreeChange} placeholder={'请选择' + label} allowClear={item.allowClear} showCheckedStrategy="SHOW_PARENT" searchPlaceholder={item.list} treeCheckable={item.treeCheckable} searchPlaceholder={'请选择' + label}
                showSearch
                treeNodeFilterProp = 'title'
                  multiple={multiple === true ? true : false}>
                  {this.renderTreeNodes(item.list, item.name, item.valueField)}
                </TreeSelect>)}
              </FormItem>
            </Col>

          );
          formItemList.push(SELECT);
        }
      });
    }

    return formItemList;
  }


  render() {
    const p = this;
    return <Form  {... { labelCol: { xs: { span: 30 }, sm: { span: p.props.labelSpan ? p.props.labelSpan : 6 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: p.props.labelSpan ? p.props.wrapperSpan : 14 } } }}>
      {this.initFormList()}
      <Col span={24} style={{ textAlign: 'right' }}>
        <Button type="primary" icon='search' onClick={() => this.onSubmit(false)}>查询</Button>
      </Col>
      {/* <Col span={2}>
      <Button type="primary" onClick={this.reset}>清空</Button>
    </Col> */}
    </Form>;
  }
}
export default Form.create({})(BasicForm);
